<template>
  <div class="online-container">
    <div class="online-top">
      <div class="tabs">
        <CustomTabs :tabList="tabsOption" :activeName="activeName" @tabSelect="tabSelectHandler" />
      </div>
      <px-form ref="formRef" class="custom-form-ui inspection-form" :model="queryParams" label-position="right" label-width="120px">
        <px-form-item label="时间" style="width: 430px">
          <px-date-picker
            v-model="dateRange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :shortcuts="shortcuts"
          />
        </px-form-item>
        <px-button type="primary" @click="queryTable">查询</px-button>
        <px-button @click="resetTable">重置</px-button>
      </px-form>
      <div class="online-chart">
        <doubleYLine :key="tablePieKey" title="水质数据趋势图" :echartsLoading="echartsLoading" :height="480" :options="trendOptions" />
      </div>
    </div>
    <div class="tableCon">
      <modelTitle title="明细" />
      <div v-loading="tableLoading" class="table-content">
        <px-table
          :data="tableData"
          class="inspection-table"
          size="small"
          height="calc(100vh -82px)"
          border
          show-overflow-tooltip
          :header-cell-class-name="tableHeaderColor"
          :cell-style="cellClassName"
        >
          <px-table-column label="序号" width="60" align="center" fixed="left">
            <template #default="{ $index }">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
            </template>
          </px-table-column>
          <px-table-column label="时间" align="left" prop="date" min-width="130" />
          <px-table-column v-for="item in tabsOptionTable" :key="item.name" :label="item.label" align="center">
            <px-table-column v-for="sub in item.subList" :key="sub.itemName" :label="sub.itemName" align="right">
              <px-table-column
                :label="`${sub.itemDesc.min ? sub.itemDesc.min : ''}${sub.itemDesc.min && sub.itemDesc.max ? '~' : ''}${sub.itemDesc.max && !sub.itemDesc.min ? '≤' : ''}${sub.itemDesc.max ? sub.itemDesc.max : ''}${sub.itemDesc.unit ? sub.itemDesc.unit : ''}`"
                align="right"
              >
                <template #default="scope">
                  <div :class="{ 'red-cell': isEmptyObject(scope.row.fault) && scope.row.fault[`${item.name}_${sub.itemName}`] }">
                    {{ scope.row.result[`${item.name}_${sub.itemName}`] ? scope.row.result[`${item.name}_${sub.itemName}`] : "-" }}
                  </div>
                </template>
              </px-table-column>
            </px-table-column>
          </px-table-column>
          <template #empty>
            <px-empty :image-size="100" />
          </template>
        </px-table>
      </div>
      <pagination
        v-if="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="inspection-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, getCurrentInstance, onMounted, computed, reactive, toRefs, nextTick } from "vue";
import doubleYLine from "@/views/machine/components/doubleYLine/index.vue";
import CustomTabs from "@/components/Tabs/index.vue";
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import { queryChildByTypeCodeAndItemValue } from "@/api/machineClass";
import { onLineWaterTest, queryScadaIndicator, getOnlineData } from "@/api/machineApi";
import type { UtilsEChartsOption } from "@pureadmin/utils";

const { proxy }: any = getCurrentInstance();

const activeName = ref("all");

const state = reactive<any>({
  spcDataList: [],
  pointData: {},
  trendOptions: null,
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    subsystem: ""
  },
  queryChartParams: {
    contentType: "LIST",
    bucketWidth: 5,
    bucketUnit: "minutes",
    point: [],
    indicators: ["FIRST", "LAST"]
  },
  total: 0,
  tableData: [],
  selectIds: [],
  pointList: []
});

const { trendOptions, pointData, queryParams, queryChartParams, total, tableData, pointList } = toRefs(state);

const echartsLoading = ref(false);

const tablePieKey = ref(Date.now());

const tableLoading = ref(false);

const dateRange = ref<any>([
  proxy.parseTime(new Date().getTime() - 4 * 60 * 60 * 1000 + 1000, "{y}-{m}-{d} {h}:{i}:{s}"),
  proxy.parseTime(new Date().getTime(), "{y}-{m}-{d} {h}:{i}:{s}")
]);

const tabsOption = ref([
  {
    name: "all",
    label: "全部",
    subList: []
  },
  {
    name: "MCHWConfig",
    label: "MCHW",
    subList: []
  },
  {
    name: "LCHWConfig",
    label: "LCHW",
    subList: []
  },
  {
    name: "HWConfig",
    label: "HW",
    subList: []
  },
  {
    name: "HHWConfig",
    label: "HHW",
    subList: []
  },
  {
    name: "CWConfig",
    label: "CW",
    subList: []
  },
  {
    name: "PCWConfig",
    label: "PCW",
    subList: []
  }
]);

const tabsOptionTable = computed(() => {
  if (activeName.value === "all") {
    return tabsOption.value.filter(e => e.name !== "all").reverse();
  } else {
    return tabsOption.value.filter(e => e.name === activeName.value);
  }
});

const tabSelectHandler = async (selectName: string) => {
  activeName.value = selectName;
  await queryTable();
};

const shortcuts = [
  {
    text: "本日",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setHours(0, 0, 0, 0);
      start.setTime(start.getTime());
      return [start, end];
    }
  },
  {
    text: "近7天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    text: "近30天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    }
  },
  {
    text: "本月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      start.setTime(start.getTime());
      return [start, end];
    }
  },
  {
    text: "本季度",
    value: () => {
      const end = new Date();
      const start = new Date();
      let currenMonth = start.getMonth();
      let quarter = Math.floor((currenMonth + 3) / 3) - 1;
      start.setMonth(quarter * 3, 1);
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      start.setTime(start.getTime());
      return [start, end];
    }
  }
];

const isEmptyObject = obj => {
  return obj && typeof obj === "object" && Object.keys(obj).length > 0;
};

// 单元格类名
const cellClassName = ({ row, column }) => {
  // console.log(row.fault, column, "999999999999999999999999999");
  // if (column.property === "fault" && isEmptyObject(row.fault)) {
  //   return {
  //     color: "#ef4444",
  //     backgroundColor: "#feecec"
  //   };
  // }
  return {};
};

const tableHeaderColor = ({ row, column, rowIndex, columnIndex }) => {
  if (rowIndex === 1 || rowIndex === 2) {
    return "bg1";
  }
  return "bg0";
};

// 合并同类项数组
const mergeDataByProperty = (arr, type) => {
  const merged = [];
  let propertyValues = {};
  const keyArr: any = Array.from(new Set(arr.map(item => item.point))) || [];
  for (const val in keyArr) {
    propertyValues[keyArr[val]] = [];
    console.log(val);
    arr.forEach(item => {
      if (item.point === keyArr[val]) {
        propertyValues[keyArr[val]].push({
          name: item[type],
          value: Number(item.last_value)
        });
      }
    });
  }
  return propertyValues;
};

const getXiasDataName = name => {
  let str = name || "";
  if (queryChartParams.value.queryTimeGranularity === "Daily") {
    return str.substring(0, 10);
  } else if (queryChartParams.value.queryTimeGranularity === "Monthly") {
    return str.substring(0, 7);
  } else {
    return str.substring(0, 4);
  }
};

// 查询
const queryTable = async () => {
  queryParams.value.subsystem = activeName.value === "all" ? "" : activeName.value;
  // let type = "";
  // switch (queryChartParams.value.queryTimeGranularity) {
  //   case "Daily":
  //     type = "day";
  //     break;
  //   case "Monthly":
  //     type = "month";
  //     break;
  //   case "Yearly":
  //     type = "year";
  //     break;

  //   default:
  //     break;
  // }
  echartsLoading.value = true;
  tableLoading.value = true;
  const params = proxy.addDateRange(queryChartParams.value, dateRange.value, "startTime", "endTime");
  // const tableParams = proxy.addDateRange(queryParams.value, dateRange.value, "reportStart", "reportEnd");
  const data: any = await onLineWaterTest(activeName.value).catch(error => {
    echartsLoading.value = false;
    tableLoading.value = false;
  });

  const dataList: any = await getOnlineData(queryParams.value).catch(error => {
    tableLoading.value = false;
  });
  tableData.value = dataList && dataList.data ? dataList.data : [];
  total.value = dataList?.total;
  pointData.value = data;

  if (data && Object.keys(data).length) {
    const arr = Object.keys(data).map(e => {
      return {
        name: e,
        conductivityPoint: data[e].Conductivity ? data[e].Conductivity : "",
        phPoint: data[e].PH ? data[e].PH : ""
      };
    });
    pointList.value = arr;
    const arrList = arr
      .map(e => e.conductivityPoint)
      .concat(arr.map(e => e.phPoint))
      .filter(e => e !== "");
    params.point = arrList;
  } else {
    params.point = [];
  }
  if (!params.point.length) {
    trendOptions.value = null;
    echartsLoading.value = false;
    tableLoading.value = false;
    return;
  }
  const res: any = await queryScadaIndicator(params).catch(error => {
    echartsLoading.value = false;
    tableLoading.value = false;
  });
  const mergeData: any = mergeDataByProperty(res.rows, "minutes") || {};
  const xData: any = Object.keys(mergeData) && Object.keys(mergeData).length ? mergeData[Object.keys(mergeData)[0]].map(e => e.name) : [];
  // Object.keys(mergeData) && Object.keys(mergeData).length ? mergeData[Object.keys(mergeData)[0]].map(e => getXiasDataName(e.name)) : [];
  // const legendData: any = Object.keys(mergeData) || [];
  const colors = ["#4786FF", "#14C7C7", "#FFB266", "#8B8AE6", "#49B0F5", "#FFA299", "#B88AE7", "#85CFF5", "#50A9C7", "#A1B0E6", "#48B48F", "#CCB18F"];
  const seriesData = Object.keys(mergeData).map((item, index) => {
    return {
      name: getName(pointList.value, `${item}`),
      yAxisIndex: getName(pointList.value, `${item}`).includes("PH") ? 0 : 1,
      type: "line",
      emphasis: {
        focus: "series",
        blurScope: "coordinateSystem"
      },
      data: mergeData[item],
      symbol: "none",
      itemStyle: {
        color: colors[index]
      }
    };
  });
  const legendData: any = seriesData.map(e => e.name) || [];
  trendOptions.value = labelLayoutFn(xData, legendData, seriesData);
  tablePieKey.value = Date.now();
  echartsLoading.value = false;
  tableLoading.value = false;
};

// 重置筛选条件
const resetTable = async () => {
  dateRange.value = [
    proxy.parseTime(new Date().getTime() - 4 * 60 * 60 * 1000 + 1000, "{y}-{m}-{d} {h}:{i}:{s}"),
    proxy.parseTime(new Date().getTime(), "{y}-{m}-{d} {h}:{i}:{s}")
  ];
  await queryTable();
};

const getName = (list, point) => {
  const foundItem = list.find(item => item.conductivityPoint === point || item.phPoint === point);
  if (!foundItem) {
    return point;
  }
  if (foundItem.conductivityPoint === point) {
    return `${foundItem.name.replace(/Config$/i, "")}-电导率`;
  } else if (foundItem.phPoint === point) {
    return `${foundItem.name.replace(/Config$/i, "")}-PH`;
  }
  return null;
};

const labelLayoutFn = (xData: any, legendData: any, seriesData: any) => {
  const options: UtilsEChartsOption = {
    grid: {
      left: "60px",
      top: "40px",
      right: "60px",
      bottom: "10px",
      containLabel: true
    },
    tooltip: {
      trigger: "axis",
      confine: true
    },
    legend: {
      type: "scroll", // 设置图例分页类型为滚动
      icon: "rect",
      orient: "horizontal", // 水平排列
      data: legendData || []
    },
    dataZoom: [
      {
        show: true,
        realtime: true,
        start: 0,
        end: 100
      },
      {
        type: "inside",
        realtime: true,
        start: 0,
        end: 100
      }
    ],
    xAxis: [
      {
        type: "category",
        boundaryGap: false,
        axisLine: { onZero: false },
        data: xData || []
      }
    ],
    yAxis: [
      {
        name: "PH",
        nameLocation: "middle", //居中
        nameGap: 80, //轴线距离
        nameRotate: 90, //字体选择角度
        alignTicks: true,
        type: "value"
      },
      {
        name: "电导率(us/cm)",
        nameLocation: "middle", //居中
        nameGap: 80, //轴线距离
        nameRotate: 90, //字体选择角度
        alignTicks: true,
        type: "value"
      }
    ],
    series: seriesData
    // series: [
    //   {
    //     name: 'Flow',
    //     type: 'line',
    //     areaStyle: {},
    //     lineStyle: {
    //       width: 1
    //     },
    //     emphasis: {
    //       focus: 'series'
    //     },
    //     data: []
    //   },
    //   {
    //     name: 'Rainfall',
    //     type: 'line',
    //     yAxisIndex: 1,
    //     areaStyle: {},
    //     lineStyle: {
    //       width: 1
    //     },
    //     emphasis: {
    //       focus: 'series'
    //     },
    //     data: []
    //   }
    // ]
  };
  return options;
};

const init = async () => {
  for (let i = 0; i < tabsOption.value.length; i++) {
    if (tabsOption.value[i].name !== "all") {
      const arr: any = await queryChildByTypeCodeAndItemValue({
        value: tabsOption.value[i].name,
        typeCode: "MCTS"
      });
      tabsOption.value[i].subList = arr.filter(e => e.itemName === "PH" || e.itemName === "Conductivity");
    }
  }
  tabsOption.value.forEach(item => {
    item.subList.forEach(e => (e.itemDesc = JSON.parse(e.itemDesc.replace(/[\r|\n|\t]/g, ""))));
  });
  console.log(tabsOption.value, "tabsOption.value");
  await queryTable();
};

const initSpcDate = () => {
  const date = new Date();
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  let lastda = date.getDate() < 10 ? "0" + (date.getDate() + 1).toString() : (date.getDate() + 1).toString();
  let year = date.getFullYear();
  let lastYear = date.getFullYear() - 1;
  return [`${lastYear}-${month}-${lastda}`, `${year}-${month}-${da}`]; // 近一年时间范围
};

onMounted(() => {
  init();
});
</script>
<style lang="scss" scoped>
.online-container {
  display: flex;
  flex-flow: column nowrap;
  gap: 16px;
  height: 100%;

  .online-top {
    padding: 16px 24px;
    background-color: #fff;
    border-radius: 4px;

    .tabs {
      margin-bottom: 9px;

      :deep(.px-tabs__nav) {
        margin-top: 0;
      }
    }
  }

  .online-chart {
    height: 480px;
  }

  .tableCon {
    display: flex;
    flex-flow: column nowrap;
    gap: 16px;
    padding: 16px 24px;
    background-color: #fff;
    border-radius: 4px;

    :deep(.px-table__header) {
      thead {
        .bg0 {
          background-color: #e7eef8 !important;
        }

        .bg1 {
          background-color: #fef5e6 !important;
        }

        .bg2 {
          background-color: #e8f8f3 !important;
        }
      }
    }
  }

  .bgDom {
    height: 16px;
    background-color: #f0f2f5;
  }

  .spc_con {
    display: flex;
    flex-flow: row wrap;
    align-items: center;
    justify-content: space-between;
    min-width: 1300px;

    .spc_item {
      width: 100%;
      height: 468px;
      margin-bottom: 20px;
      border-radius: 4px;
    }
  }

  :deep(.px-table .px-table__header-wrapper th) {
    background-color: #e7eef8;
  }
}

:deep(.pagination-container) {
  height: 32px;
  padding: 0 !important;
  margin: 0;
}

:deep(td.px-table__cell:has(.red-cell)) {
  background-color: #feecec !important;
}

:deep(.red-cell) {
  color: #ef4444 !important;
}
</style>
